package com.project.seckill.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

/**
 * Created by yachao on 2018/6/24.
 */
@Slf4j
public class Md5Util {

    private static final String SALT = "1a2b3c4d";

    public static String md5(String data) {
        return DigestUtils.md5Hex(data);
    }

    public static String inputPassToFormPass(String inputPassword) {
        StringBuffer buffer = new StringBuffer("");
        buffer.append(SALT.charAt(0))
                .append(SALT.charAt(2))
                .append(inputPassword)
                .append(SALT.charAt(5))
                .append(SALT.charAt(4));

        String result = md5(buffer.toString());
        log.info("Input password '{}' to form password '{}'.", inputPassword, result);
        return result;
    }

    public static String formPassToDbPass(String formPassword, String salt) {
        if (StringUtils.isBlank(salt))
            salt = SALT;
        Objects.requireNonNull(salt.length() >= 5, "The length of salt cannot be less than 5.");

        StringBuffer buffer = new StringBuffer("");
        buffer.append(salt.charAt(0))
                .append(salt.charAt(2))
                .append(formPassword)
                .append(salt.charAt(5))
                .append(salt.charAt(4));

        String result = md5(buffer.toString());
        log.info("Form password '{}' to DB password '{}'.", formPassword, result);
        return result;
    }

    public static String inputPasswordToDbPass(String inputPassword, String saltDB) {
        return formPassToDbPass(inputPassToFormPass(inputPassword), saltDB);
    }

    public static void main(String[] args) {
        String data = "jangz";
        String result = inputPasswordToDbPass(data, SALT);
        System.out.println(result);
    }

}
